package com.magina.project.mgdb.service;

import com.magina.project.mgdb.dao.TestDemoRepository;
import com.magina.project.mgdb.entity.TestDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class MgdbTemplateService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TestDemoRepository testDemoRepository;

    public Object testTemplateMethod(){
        List list = new ArrayList();
        for (int i = 0; i < 3; i++) {
            TestDemo demo = new TestDemo();
            demo.setId(UUID.randomUUID().toString());//2.1.3版本mongoDb jar包将id和ObjectId 合并了
            demo.setName("name"+i);
            list.add(demo);
        }
        mongoTemplate.insert(list,"magina001");
        List<TestDemo> demoList = mongoTemplate.findAll(TestDemo.class,"magina001");
        return demoList;
    }

    public Object testRepositoryMehod(){
        List list = new ArrayList();
        for (int i = 0; i < 3; i++) {
            TestDemo demo = new TestDemo();
            demo.setName("name"+i);
            list.add(demo);
            testDemoRepository.save(demo);
        }
//        System.out.println(1/0);
        return testDemoRepository.findAll();
    }
    @Transactional
    public Object testTemplateMethodWithTran() {
        TestDemo demo = new TestDemo();
        demo.setId(UUID.randomUUID().toString());
        demo.setName("name" + UUID.randomUUID().toString());
        mongoTemplate.insert(demo, "magina001");
        //需要配置mongoDB集群,单节点的mongoDB不支持事务
//        System.out.println(1/0);
        List<TestDemo> demoList = mongoTemplate.findAll(TestDemo.class, "magina001");
        return demoList;
    }

    public Object testRepositoryMehodRemove(){
        Query query = Query.query(Criteria.where("name").is("name1"));
        //查询出符合条件的第一个结果，并将符合条件的数据删除,只会删除第一条
//        query = Query.query(Criteria.where("name").is("name1"));
//        TestDemo testDemo = mongoTemplate.findAndRemove(query, TestDemo.class);

        //查询出符合条件的所有结果，并将符合条件的所有数据删除
//        query = Query.query(Criteria.where("author").is("yinjihuan"));
//        List<TestDemo> articles = mongoTemplate.findAllAndRemove(query, TestDemo.class);

        //删除集合，可传实体类，也可以传名称
//        mongoTemplate.dropCollection(TestDemo.class);
//        mongoTemplate.dropCollection("magina001");

        //可以传入collectionName / className
//       return  mongoTemplate.remove(query,"magina001");
       return  mongoTemplate.remove(query,TestDemo.class);
    }
}
